/*
 * @Author: 13558093597 277098906@qq.com
 * @Date: 2025-06-13 16:37:28
 * @LastEditors: 13558093597 277098906@qq.com
 * @LastEditTime: 2025-06-27 15:36:02
 * @FilePath: \mes_app\lib\components\home\job.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:mes_app/color/hex.dart';
import 'package:mes_app/extensions/ex_widget.dart';
import 'package:mes_app/model/job.dart';
import 'package:mes_app/ui/scroll_refresh_config.dart';
import 'package:mes_app/utils/styles.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

///
/// 报工
///
class HomeJobController extends GetxController
    with GetTickerProviderStateMixin {
  List<String> tags = ['全部', '未开工', '进行中', '已完成', '已关闭', '已暂停', '延迟', '逾期'];

  RefreshController refreshController = RefreshController();

  RxList<JobModel> pageList = RxList([]);

  late TabController tabController;

  @override
  void onInit() {
    tabController = TabController(length: tags.length, vsync: this);
    initData();
    super.onInit();
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    pageList.removeRange(0, pageList.length);
    initData();
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 45) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }

  void initData() {
    for (var i = 0; i < 10; i++) {
      pageList.add(
        JobModel(
          title: generateFixedLengthRandom(),
          code: generateAlphanumericCode(),
          name: '站点一',
          processes: '工序一',
          responsible: '赵莉莉',
          createTime: DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()),
        ),
      );
    }
  }

  String generateFixedLengthRandom([int length = 4]) {
    final random = Random();
    return List.generate(length, (_) => random.nextInt(10).toString()).join();
  }

  String generateAlphanumericCode([int length = 10]) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    final random = Random();
    return List.generate(length, (_) => chars[random.nextInt(chars.length)])
        .join();
  }

  final GlobalKey navBarKey = GlobalKey();

  TDDrawer? tdDrawer;

  void createdTDDrawer(BuildContext context) {
    if (tdDrawer == null) {
      var renderBox =
          navBarKey.currentContext?.findRenderObject() as RenderBox?;
      tdDrawer = TDDrawer(
        context,
        visible: false,
        drawerTop: renderBox?.size.height,
        width: Get.width * 0.6,
        items: List.generate(30, (index) => TDDrawerItem(title: '菜单$index'))
            .toList(),
        onItemClick: (index, item) {
          debugPrint('drawer item被点击，index：$index，title：${item.title}');
          tdDrawer?.close();
        },
      );
    }
    tdDrawer?.show();
  }
}

class HomeJobView extends GetView<HomeJobController> {
  const HomeJobView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: HexColor(HexColor.colorF9f9),
      appBar: TDNavBar(
        key: controller.navBarKey,
        title: '工单任务',
        titleColor: HexColor(HexColor.color0000),
        titleFontWeight: FontWeight.w700,
        titleFont: Font(size: StylesUtils.fontSize16.toInt(), lineHeight: 1),
        backgroundColor: Colors.white,
        screenAdaptation: true,
        useDefaultBack: false,
        useBorderStyle: true,
        titleMargin: 0,
        border: TDNavBarItemBorder(
          width: 1,
          color: HexColor(HexColor.colorF9f9),
        ),
      ),
      body: Column(
        children: [
          Container(
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  height: 56,
                  padding: EdgeInsets.only(left: 10, top: 10, bottom: 10),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 1,
                        color: HexColor(HexColor.colorF2f2),
                      ),
                      top: BorderSide(
                        width: 1,
                        color: HexColor(HexColor.colorF2f2),
                      ),
                    ),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      TDSearchBar(
                        placeHolder: '请输入任务名称/工单号',
                        backgroundColor: HexColor(HexColor.colorF5f5),
                        padding: EdgeInsets.zero,
                        autoHeight: true,
                      ).expand(),
                      Container(
                        margin: EdgeInsets.only(left: 20, right: 20),
                        width: 36,
                        height: 36,
                        alignment: Alignment.center,
                        child: SvgPicture.network(
                          'https://cdn8.axureshop.com/demo2023/2215319/images/%E7%B3%BB%E7%BB%9F%E7%BB%84%E4%BB%B6/u555.svg',
                          width: 15,
                          height: 16,
                          fit: BoxFit.fill,
                        ),
                      ).onTap(() {
                        controller.createdTDDrawer(context);
                      }),
                    ],
                  ),
                ),
                Container(
                  height: 40,
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 1,
                        color: HexColor(HexColor.colorF2f2),
                      ),
                    ),
                  ),
                  child: TDTabBar(
                    tabs: controller.tags
                        .map(
                          (str) => TDTab(
                            text: str,
                          ),
                        )
                        .toList(),
                    labelColor: HexColor(HexColor.color6190),
                    labelStyle: StylesUtils.customTextStyle(
                      fontSize: StylesUtils.defaultFontSize,
                      color: HexColor.color3333,
                    ),
                    unselectedLabelColor: HexColor(HexColor.color3333),
                    unselectedLabelStyle: StylesUtils.customTextStyle(
                      fontSize: StylesUtils.defaultFontSize,
                      color: HexColor.color3333,
                    ),
                    controller: controller.tabController,
                    labelPadding: EdgeInsets.symmetric(horizontal: 10),
                    isScrollable: true,
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: Obx(
              () => ScrollRefreshConfig(
                refreshController: controller.refreshController,
                onRefresh: controller.onRefresh,
                onLoading: controller.onLoading,
                child: ListView.builder(
                  itemBuilder: (c, i) {
                    var row = controller.pageList[i];
                    return Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(top: 20),
                      child: Container(
                        width: 355,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(
                            color: HexColor(HexColor.colorF2f2),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(6.r),
                        ),
                        child: Column(
                          children: [
                            Container(
                              height: 50,
                              padding: EdgeInsets.symmetric(horizontal: 15),
                              decoration: BoxDecoration(
                                border: Border(
                                  bottom: BorderSide(
                                    width: 1,
                                    color: HexColor(HexColor.colorF2f2),
                                  ),
                                ),
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  TDText(
                                    '新产品工单任务${row.title}',
                                    style: StylesUtils.customTextStyle(
                                      color: HexColor.color3333,
                                      fontWeight: FontWeight.w700,
                                    ),
                                  ),
                                  Icon(TDIcons.chevron_right_s).onTap(() {})
                                ],
                              ),
                            ),
                            Container(
                              height: 40,
                              padding: EdgeInsets.symmetric(horizontal: 15),
                              alignment: Alignment.centerLeft,
                              child: TDText(
                                '任务编号：${row.code}',
                                style: StylesUtils.customTextStyle(
                                  color: HexColor.color3333,
                                ),
                              ),
                            ),
                            Container(
                              height: 40,
                              padding: EdgeInsets.symmetric(horizontal: 15),
                              alignment: Alignment.centerLeft,
                              child: TDText(
                                '站点名称：${row.processes}',
                                style: StylesUtils.customTextStyle(
                                  color: HexColor.color3333,
                                ),
                              ),
                            ),
                            Container(
                              height: 40,
                              padding: EdgeInsets.symmetric(horizontal: 15),
                              alignment: Alignment.centerLeft,
                              child: TDText(
                                '工序名称：${row.name}',
                                style: StylesUtils.customTextStyle(
                                  color: HexColor.color3333,
                                ),
                              ),
                            ),
                            Container(
                              height: 40,
                              padding: EdgeInsets.symmetric(horizontal: 15),
                              alignment: Alignment.centerLeft,
                              child: TDText(
                                '负责人：${row.responsible}',
                                style: StylesUtils.customTextStyle(
                                  color: HexColor.color3333,
                                ),
                              ),
                            ),
                            Container(
                              height: 40,
                              padding: EdgeInsets.symmetric(horizontal: 15),
                              alignment: Alignment.centerLeft,
                              child: TDText(
                                '派工时间：${row.createTime}',
                                style: StylesUtils.customTextStyle(
                                  color: HexColor.color3333,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: controller.pageList.length,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
